<template>
  <div style="width: 800px">
    <div>
      <el-button type="primary" @click="back()" style="margin-bottom: 20px;">返回</el-button>
      <el-button type="primary" @click="openAll()">全部展开</el-button>
      <el-button type="primary" plain @click="closeAll()">全部收起</el-button>
    </div>
    <el-form
      :model="dataForm"
      :rules="rules"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
    >
      <div v-for="(item, index) in dataForm.questionTitleList" style="display: flex;margin-left: 50px;">
        <div style="margin-top: 10px;">{{index+1}}.</div>
        <div>
          <el-form-item
            :key="`${index}questionTitle`"
            label="题目"
            :rules="rules.questionTitle"
            :prop="'questionTitleList.'+index+'.questionTitle'"
          >
            <el-input style="width: 600px;" v-model.trim="item.questionTitle" type="textarea" :rows="3"></el-input>
          </el-form-item>
          <div v-show="item.open">
            <el-form-item
              label="题目类型"
              :key="`${index}questionType`"
              :rules="rules.questionType"
              :prop="'questionTitleList.'+index+'.questionType'">
              <el-select v-model="item.questionType" @change="clearCurrent(index)" placeholder="">
                <el-option v-for="item in options" :key="item.val" :label="item.label" :value="item.val"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-for="(itemChild, indexChild) in item.optionList"
              :label="opationChange[indexChild]"
              :key="`${index}${indexChild}`"
              :rules="rules.optionContent"
              :prop="'questionTitleList.'+index+'.optionList.'+indexChild+'.optionContent'"
              v-if="itemChild.isAlive !== 0">
              <el-input v-model.trim="itemChild.optionContent" style="width: 400px;"></el-input>
              <el-checkbox v-model="itemChild.isTrue" style="margin: 0 10px;">设为正确答案</el-checkbox>
              <el-button v-if="indexChild>1" type="danger" @click="optionDelete(index, indexChild)">删除</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="optionAdd(index)">增加选项</el-button>
            </el-form-item>
            <el-form-item label="解析" prop="buttonDesc">
              <el-input v-model.trim="item.questionExplain" type="textarea" :rows="3"></el-input>
            </el-form-item>
          </div>
          <el-form-item>
            <el-button v-if="hasPaper!==1" type="danger" @click="questionDelete(index)">删除上题</el-button>
            <el-button type="primary" plain @click="()=> item.open = !item.open ">{{item.open?'收起':'展开'}}</el-button>
          </el-form-item>
        </div>
      </div>
      <el-form-item label="出题顺序（不选按编辑顺序默认排序，可多选）" label-width="320px" style="margin-left: 106px;">
        <el-checkbox v-model="questionSore" style="margin: 0 10px;">打乱题目顺序</el-checkbox>
        <el-checkbox v-model="optionSore">打乱选项顺序</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button v-if="hasPaper!==1" type="success" @click="questionAdd">新增题目</el-button>
        <el-button type="primary" @click="questionSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style>

</style>
<script>

  export default {
    data() {
      return {
        url: '',
        dialogVisible: false,
        dialogImageUrls: '',
        dataForm: {
          questionTitleList: [],
        },
        questionSore: false,
        optionSore: false,
        questionData: {},
        options: [
          {
            val: 1,
            label: '单选'
          },
          {
            val: 2,
            label: '多选'
          }
        ],
        opationChange: ['选项A', '选项B', '选项C', '选项D', '选项E', '选项F', '选项G', '选项H', '选项I', '选项J', '选项K', '选项L', '选项M', '选项N', '选项O'],
        rules: {
          questionTitle: [{required: true, message: '题目不能为空', trigger: 'blur'}],
          questionType: [{required: true, message: '请选择题目类型', trigger: 'change'}],
          optionContent: [{required: true, message: '选项不能为空', trigger: 'change'}],
        },
        hasPaper: 0,
        chapterId: '',
        bookId: '',
        id: ''
      }
    },
    mounted() {
    },
    methods: {
      init(bookId, id) {
        this.bookId = bookId
        this.chapterId = id
        let obj = {
          chapterId: id,
          bookId: bookId,
        }
        this.$http({
          url: this.$http.adornUrl(
            `/college/collegecoursepaper/list`
          ),
          method: 'get',
          params: this.$http.adornParams(obj)
        }).then(({data}) => {
          if (data && data.code === 0) {
            if (data.paperInfo) {
              this.hasPaper = 1
              let questList = data.paperInfo.questionTitleList
              this.id = data.paperInfo.id
              questList.map((item, index) => {
                questList[index].open = false
                item.optionList.map((itemchild, indexchild) => {
                  if (itemchild.isTrue === 1) {
                    item.optionList[indexchild].isTrue = true
                  }
                })
              })
              this.dataForm.questionTitleList = questList
              switch (data.paperInfo.questionSort) {
                case 1:
                  this.questionSore = false
                  this.optionSore = false
                  break;
                case 2:
                  this.questionSore = true
                  this.optionSore = false
                  break;
                case 3:
                  this.questionSore = false
                  this.optionSore = true
                  break;
                case 4:
                  this.questionSore = true
                  this.optionSore = true
                  break;
                default:
                  this.questionSore = false
                  this.optionSore = false
              }
              console.log(this.dataForm)
            } else {
              this.hasPaper = 0
            }
          }
        })
      },
      clearCurrent(index) {
        this.dataForm.questionTitleList[index].optionList.map((item,indexOpt)=> {
          this.dataForm.questionTitleList[index].optionList[indexOpt].isTrue = false
        })
        this.dataForm = {...this.dataForm}
      },
      questionAdd() {
        this.dataForm.questionTitleList.push({
          optionList: [
            {
              isTrue: false,
              optionContent: "",
            },
            {
              isTrue: false,
              optionContent: "",
            }
          ],
          chapterId: this.chapterId,
          paperId: 0,
          questionExplain: "",
          questionTitle: "",
          questionType: 1,
          open: true,
        })
        this.dataForm = this.dataForm
      },
      questionSave() {
        let questionTypeRightNum = true
        let questionTypeRightNumText = ''
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            let arr = JSON.parse(JSON.stringify(this.dataForm.questionTitleList))
            // for in可以break
            for (let index in arr) {
              // 0:单选。1：多选
              let questionType = arr[index].questionType
              let isTrueNum = 0
              arr[index].optionList.map((itemChild, indexChild) => {
                arr[index].optionList[indexChild].isTrue = itemChild.isTrue ? 1 : 0
                if(itemChild.isTrue) {
                  isTrueNum++
                }
              })
              if(isTrueNum<1) {
                questionTypeRightNum = false
                questionTypeRightNumText = `题目${parseInt(index)+1}，请设置正确答案～`
                console.log(questionTypeRightNumText)
                break
              }
              if(questionType === 2 && isTrueNum<2) {
                questionTypeRightNum = false
                questionTypeRightNumText = `题目${parseInt(index)+1}，多选必须要设置2个及以上正确答案～`
                console.log(questionTypeRightNumText)
                break
              }
              if(questionType === 1 && isTrueNum>1) {
                questionTypeRightNum = false
                questionTypeRightNumText = `题目${parseInt(index)+1}，单选只能设置1个正确答案～`
                console.log(questionTypeRightNumText)
                break
              }
            }
            if(!questionTypeRightNum) {
              this.$message.error(questionTypeRightNumText)
              return false
            }
            this.questionData = {
              id: this.id,
              chapterId: this.chapterId,
              bookId: this.bookId,
              questionSort: this.questionSore ? this.optionSore ? 4 : 2 : this.optionSore ? 3 : 1,
              questionTitleList: arr,
              questionNum: arr.length
            }
            this.$http({
              url: this.$http.adornUrl(
                `/college/collegecoursepaper/${this.hasPaper == 1 ? 'update' : 'save'}`
              ),
              method: 'post',
              data: this.$http.adornData(this.questionData)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 500,
                  onClose: () => {
                    this.init(this.bookId, this.chapterId);
                  }
                });
              } else {
                this.$message.error(data.msg)
              }
            });
          }
        })
      },
      openAll() {
        this.dataForm.questionTitleList.map((item, index) => {
          this.dataForm.questionTitleList[index].open = true
        })
      },
      closeAll() {
        this.dataForm.questionTitleList.map((item, index) => {
          this.dataForm.questionTitleList[index].open = false
        })
      },
      questionDelete(index) {
        this.dataForm.questionTitleList.splice(index, 1)
      },
      optionAdd(index) {
        this.dataForm.questionTitleList[index].optionList.push({
          isTrue: false,
          optionContent: "",
        })
      },
      optionDelete(index, indexChild) {
        if (this.dataForm.questionTitleList[index].optionList[indexChild].id) {
          this.dataForm.questionTitleList[index].optionList[indexChild].isAlive = 0
          this.dataForm = {...this.dataForm}
        } else {
          this.dataForm.questionTitleList[index].optionList.splice(indexChild, 1)
        }
      },
      back() {
        this.$emit("refresh", this.bookId);
      }
    }
  }
</script>
